import '../utils/http/http_client.dart';
import '../models/product_model.dart';
import '../models/thing_model.dart';


/// 产品服务提供者
class ProductProvider {
  final HttpClient _httpClient = HttpClient();

  /// 获取产品列表
  /// 
  /// [pageNum] 页码，默认为1
  /// [pageSize] 每页记录数，默认为10
  /// [productName] 产品名称（可选）
  /// [productKey] 产品标识码（可选）
  /// [nodeType] 节点类型（1:直连设备 2:网关设备 3:子设备）（可选）
  /// [protocolType] 通信协议（可选）
  /// [status] 状态（0:开发中 1:已发布）（可选）
  /// [hasModel] 是否有物模型（可选）
  Future<ProductListResponse> getProductList({
    int pageNum = 1,
    int pageSize = 10,
    String? productName,
    String? productKey,
    int? nodeType,
    String? protocolType,
    int? status,
    bool? hasModel,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'pageNum': pageNum,
        'pageSize': pageSize,
      };
      
      // 添加可选参数
      if (productName != null && productName.isNotEmpty) {
        params['productName'] = productName;
      }
      if (productKey != null && productKey.isNotEmpty) {
        params['productKey'] = productKey;
      }
      if (nodeType != null) {
        params['nodeType'] = nodeType;
      }
      if (protocolType != null && protocolType.isNotEmpty) {
        params['protocolType'] = protocolType;
      }
      if (status != null) {
        params['status'] = status;
      }
      if (hasModel != null) {
        params['hasModel'] = hasModel;
      }
      
      final response = await _httpClient.get(
        '/product/product/list',
        params: params,
      );
      
      return ProductListResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取产品详情
  /// 
  /// [productId] 产品ID
  Future<ProductDetailResponse> getProductDetail(int productId) async {
    try {
      final response = await _httpClient.get('/product/product/$productId');
      return ProductDetailResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 根据产品标识码获取产品详情
  /// 
  /// [productKey] 产品标识码
  Future<ProductDetailResponse> getProductByKey(String productKey) async {
    try {
      final response = await _httpClient.get('/product/product/key/$productKey');
      return ProductDetailResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取物模型列表
  /// 
  /// [pageNum] 页码，默认为1
  /// [pageSize] 每页记录数，默认为10
  /// [productId] 产品ID（可选）
  /// [modelName] 模型名称（可选）
  /// [status] 模型状态（0:草稿 1:已发布）（可选）
  Future<ThingModelListResponse> getThingModelList({
    int pageNum = 1,
    int pageSize = 10,
    int? productId,
    String? modelName,
    int? status,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'pageNum': pageNum,
        'pageSize': pageSize,
      };
      
      // 添加可选参数
      if (productId != null) {
        params['productId'] = productId;
      }
      if (modelName != null && modelName.isNotEmpty) {
        params['modelName'] = modelName;
      }
      if (status != null) {
        params['status'] = status;
      }
      
      final response = await _httpClient.get(
        '/product/model/list',
        params: params,
      );
      
      return ThingModelListResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 根据产品ID获取物模型数据
  ///
  /// [productId] 产品ID
  /// 返回物模型JSON数据，包含产品的属性、服务和事件定义
  Future<DeviceThingModelResponse> getProductThingModel(int productId) async {
    try {
      final response = await _httpClient.get('/product/model/json/$productId');
      return DeviceThingModelResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取无物模型的产品列表
  /// 
  /// 查询所有没有关联物模型的产品
  /// [pageNum] 页码，默认为1
  /// [pageSize] 每页记录数，默认为10
  /// [productName] 产品名称（可选）
  /// [productKey] 产品标识码（可选）
  /// [nodeType] 节点类型（可选）
  /// [status] 状态（可选）
  Future<ProductListResponse> getProductsWithoutModel({
    int pageNum = 1,
    int pageSize = 10,
    String? productName,
    String? productKey,
    int? nodeType,
    int? status,
  }) async {
    try {
      final Map<String, dynamic> params = {
        'pageNum': pageNum,
        'pageSize': pageSize,
        'withoutModel': true,
      };
      
      // 添加可选参数
      if (productName != null && productName.isNotEmpty) {
        params['productName'] = productName;
      }
      if (productKey != null && productKey.isNotEmpty) {
        params['productKey'] = productKey;
      }
      if (nodeType != null) {
        params['nodeType'] = nodeType;
      }
      if (status != null) {
        params['status'] = status;
      }
      
      final response = await _httpClient.get(
        '/product/product/list',
        params: params,
      );
      
      return ProductListResponse.fromJson(response);
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取产品总数
  /// 
  /// 返回系统中的产品总数
  Future<int> getProductCount() async {
    try {
      // 请求一页数据但只需要总数
      final response = await getProductList(pageNum: 1, pageSize: 1);
      return response.total;
    } catch (e) {
      rethrow;
    }
  }
  
  /// 获取无物模型产品总数
  /// 
  /// 返回系统中没有关联物模型的产品总数
  Future<int> getProductsWithoutModelCount() async {
    try {
      // 请求一页数据但只需要总数
      final response = await getProductsWithoutModel(pageNum: 1, pageSize: 1);
      return response.total;
    } catch (e) {
      rethrow;
    }
  }

  /// 获取主页所需统计数据
  /// 
  /// 返回产品总数和无物模型产品总数
  Future<Map<String, int>> getHomeStatistics() async {
    try {
      // 改为获取本地数据，避免调用不存在的API
      int productCount = 0;
      int productsWithoutModelCount = 0;
      
      try {
        productCount = await getProductCount();
      } catch (e) {
        // 如果获取失败，使用默认值
      }
      
      try {
        productsWithoutModelCount = await getProductsWithoutModelCount();
      } catch (e) {
        // 如果获取失败，使用默认值
      }
      
      return {
        'productCount': productCount,
        'productsWithoutModelCount': productsWithoutModelCount,
      };
    } catch (e) {
      rethrow;
    }
  }
} 

/// 设备物模型响应数据
class DeviceThingModelResponse {
  final String msg;
  final String modelJson;
  final int code;
  final int productId;
  
  DeviceThingModelResponse({
    required this.msg,
    required this.modelJson,
    required this.code,
    required this.productId,
  });
  
  factory DeviceThingModelResponse.fromJson(Map<String, dynamic> json) {
    return DeviceThingModelResponse(
      msg: json['msg'] ?? '',
      modelJson: json['modelJson'] ?? '{}',
      code: json['code'] ?? 0,
      productId: json['productId'] ?? 0,
    );
  }
} 